package com.xinjian.jianba.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands.DistanceUnit;
import org.springframework.data.redis.connection.RedisGeoCommands.GeoLocation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.xinjian.jianba.dao.dwmart.OnekeyMatchDao;
import com.xinjian.jianba.dao.dwmart.UserOnekeyDao;
import com.xinjian.jianba.dao.dwmid.ShopListDao;
import com.xinjian.jianba.dao.dwmid.UserInfoDao;
import com.xinjian.jianba.dao.dwmid.UserLableDao;
import com.xinjian.jianba.dao.dwmid.UserRelationDao;
import com.xinjian.jianba.dao.dwmid.UserSignDao;
import com.xinjian.jianba.dto.AgreeMeetDto;
import com.xinjian.jianba.dto.CancleMeetDto;
import com.xinjian.jianba.dto.InviteMeetDto;
import com.xinjian.jianba.dto.LableTreeDto;
import com.xinjian.jianba.dto.MeetAddressDto;
import com.xinjian.jianba.dto.MeetAddressVo;
import com.xinjian.jianba.dto.MeetListDto;
import com.xinjian.jianba.dto.MeetListResultDto;
import com.xinjian.jianba.dto.RefuseMeetDto;
import com.xinjian.jianba.dto.RevokeMeetDto;
import com.xinjian.jianba.dto.StartMeetDto;
import com.xinjian.jianba.dto.StartMeetResultDto;
import com.xinjian.jianba.dto.es.EsServiceResult;
import com.xinjian.jianba.dto.geo.GeoResult;
import com.xinjian.jianba.dto.geo.Results;
import com.xinjian.jianba.enity.OnekeyMatchEntity;
import com.xinjian.jianba.enity.ShopListEntity;
import com.xinjian.jianba.enity.SiteListEntity;
import com.xinjian.jianba.enity.UserInfoEnity;
import com.xinjian.jianba.enity.UserOnekeyEnity;
import com.xinjian.jianba.enity.UserRelationEntity;
import com.xinjian.jianba.enity.UserSignEnity;
import com.xinjian.jianba.exception.BusinessException;
import com.xinjian.jianba.exception.Page;
import com.xinjian.jianba.exception.Pageable;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.exception.ResponseCodeAwareException;
import com.xinjian.jianba.service.LableService;
import com.xinjian.jianba.service.MeetService;
import com.xinjian.jianba.service.RedisService;
import com.xinjian.jianba.service.SiteListService;
import com.xinjian.jianba.service.YueJianService;
import com.xinjian.jianba.utils.Constants;
import com.xinjian.jianba.utils.DateUtil;
import com.xinjian.jianba.utils.EsUtil;
import com.xinjian.jianba.utils.JianBaEnum;
import com.xinjian.jianba.utils.JsonUtil;
import com.xinjian.jianba.utils.ListUtil;
import com.xinjian.jianba.utils.SMSUtils;

@Service
public class MeetServiceImpl implements MeetService {
	private static final Logger LOGGER = LoggerFactory.getLogger(MeetServiceImpl.class);

	@Autowired
	private RedisService redisService;
	@Autowired
	private UserLableDao userLableDao;
//	@Autowired
//	private UserOnekeyDao userOnekeyDao;
	@Autowired
	private UserRelationDao userRelationDao;
	@Autowired
	public UserInfoDao userInfoDao;

	@Autowired
	public UserSignDao userSignDao;
	@Autowired
	public OnekeyMatchDao onekeyMatchDao;

	@Autowired
	public LableService lableService;

	@Autowired
	public SiteListService siteListService;

	@Autowired
	public YueJianService yueJianService;
	@Autowired
	public ShopListDao shopListDao;
	@Value("${spring.near.geo.db}")
	private String geoDb;

	@Value("${spring.near.geo.male.db}")
	private String maleGeodb;

	@Value("${spring.near.geo.female.db}")
	private String femaleGeodb;

	/**
	 * 用户点击约见按钮后，保存用户此时的位置数据，并返回给用户可约见的用户列表。
	 * 
	 * @author liuhaitao
	 * @param startMeetDto
	 * @return
	 * @throws Exception
	 *
	 */
//	@Override
//	@Transactional(rollbackFor = Exception.class)
//	public Page<StartMeetResultDto> startMeet(StartMeetDto startMeetDto) throws Exception {
//		List<StartMeetResultDto> resultList = new ArrayList<StartMeetResultDto>();
//
//		// 1、保存数据----保存到表与缓存中
//		saveStartMeet(startMeetDto);
//		int count = 0;
//		List<Long> userIdList = new ArrayList<Long>();
//		// key=userId,value=距离
//		Map<Long, String> userDistanceMap = new HashMap<Long, String>();
//		// 2、计算距离内的用户
//		count = getMeetDistance(startMeetDto, count, userIdList, userDistanceMap);
//
//		// 3、组装用户数据
//		assembleUserData(resultList, userIdList, userDistanceMap);
//
//		Pageable pageable = new Pageable(startMeetDto.getPageNumber(), startMeetDto.getPageSize());
//		LOGGER.info("-----meet-count-------" + count);
//
//		Page<StartMeetResultDto> pageVo = new Page<StartMeetResultDto>(resultList, count, pageable);
//		return pageVo;
//	}

	/**
	 * 组装用户数据
	 *
	 * @author liuhaitao
	 * @param
	 * @return
	 * @exception
	 * @since JDK 1.8
	 */
	private void assembleUserData(List<StartMeetResultDto> resultList, List<Long> userIdList, Map<Long, String> userDistanceMap) {
		if (!CollectionUtils.isEmpty(userIdList) && userIdList.size() > 0) {

			// key =userId ,value= UserInfoEnity
			Map<Long, UserInfoEnity> userInfoMap = assembleUserInfo(userIdList);

			for (Long id : userIdList) {
				StartMeetResultDto resultDto = new StartMeetResultDto();
				resultDto.setId(id);
				if (userInfoMap != null && userInfoMap.get(id) != null) {
					UserInfoEnity userInfo = userInfoMap.get(id);
					setDefaultValue(resultDto, userInfo);
					if (userDistanceMap != null) {
						resultDto.setDistance(userDistanceMap.get(id));
					}
				}
				resultList.add(resultDto);
			}
		}
	}

	/**
	 * 设置用户默认值
	 *
	 * @param
	 * @return
	 * @exception
	 */
	private void setDefaultValue(StartMeetResultDto resultDto, UserInfoEnity userInfo) {
		if (userInfo != null) {
			if (StringUtils.isBlank(userInfo.getNickname())) {
				if (userInfo.getSex() != null && userInfo.getSex().intValue() == 0) {
					resultDto.setNickname("帅哥");
				} else {
					resultDto.setNickname("美女");
				}
			} else {
				resultDto.setNickname(userInfo.getNickname());
			}

			UserSignEnity userSignEnity = userSignDao.selectByUserId(userInfo.getId());
			if (userSignEnity != null) {
				resultDto.setUserSign(userSignEnity.getSignvalue());
			}

			if (userInfo.getBirthday() != null) {
				Date bir = DateUtil.parse("1991-01-01");
				resultDto.setAge(DateUtil.getAge(bir));
			} else {
				resultDto.setAge(DateUtil.getAge(userInfo.getBirthday()));
			}

			if (userInfo.getBirthday() == null) {
				Date bir = DateUtil.parse("1991-01-01");
				resultDto.setConstellation(DateUtil.getConstellation(bir));
			} else {
				resultDto.setConstellation(DateUtil.getConstellation(userInfo.getBirthday()));
			}
			resultDto.setSex(userInfo.getSex());
			resultDto.setUserLogo(userInfo.getUserLogo());
			List<LableTreeDto> lableTree = lableService.UserlableTree(userInfo.getId());
			resultDto.setLableList(lableTree);

		}

	}

	/**
	 * 计算用户距离
	 *
	 * @author liuhaitao
	 * @param userIdList
	 * @param userDistanceMap
	 * @param totalPages 
	 * @param
	 * @return
	 * @throws Exception
	 * @exception
	 * @since JDK 1.8
	 */
	private Integer getMeetDistance(StartMeetDto startMeetDto, int count, List<Long> userIdList, Map<Long, String> userDistanceMap)
			throws Exception {
		Integer size = 0;
		String db = geoDb;
		//默认看男女
		if (startMeetDto.getMeetType() != null) {
			//看男女
			if (startMeetDto.getMeetType() == 0) {
				db = geoDb;
				//只看男
			} else if (startMeetDto.getMeetType() == 1) {
				db = maleGeodb;
				//只看女
			} else if (startMeetDto.getMeetType() == 2) {
				db = femaleGeodb;
			}
		} else {
			db = geoDb;
		}

		LOGGER.info("------getMeetDistance-------" + db);

		GeoResults<GeoLocation<String>> geoResults = redisService.radiusGeo(db, startMeetDto.getLngfloat().doubleValue(), startMeetDto
				.getLatfloat().doubleValue(), Integer.MAX_VALUE, null, DistanceUnit.METERS);
		GeoResult geoResult = JsonUtil.json2Obj(JsonUtil.getJsonString(geoResults), GeoResult.class);
		List<Long> idList = new ArrayList<Long>();
		long curId = Long.parseLong(startMeetDto.getId());
		geoResult.getResults().stream().forEach(result -> {

			if (StringUtils.isNotBlank(result.getContent().getName())) {
				long id = Long.parseLong(result.getContent().getName());
				if (id != curId) {
					idList.add(id);
				}
			}
		});
		if (idList.size() > 0) {
			size = idList.size();
			LOGGER.info("------idList-------" + idList);
			getPage(idList, startMeetDto, count, userIdList);

			if (!CollectionUtils.isEmpty(userIdList) && userIdList.size() > 0) {
				for (Results result : geoResult.getResults()) {
					if (StringUtils.isNotBlank(result.getContent().getName())) {
						long userId = Long.parseLong(result.getContent().getName());
						if (userIdList.contains(userId)) {
							if (result.getDistance() != null) {
								userDistanceMap.put(userId, result.getDistance().getValue() + "");
							}
						}
					}
				}
			}
		}
		return size;
	}

	// 数据分页
	private void getPage(List<Long> idList, StartMeetDto startMeetDto, int count, List<Long> userIdList) {

		if (!CollectionUtils.isEmpty(idList) && idList.size() > 0) {
			int totalCount = idList.size();
			int startIndex = (startMeetDto.getPageNumber() - 1) * startMeetDto.getPageSize() + 1;
			int endIndex = startMeetDto.getPageNumber() * startMeetDto.getPageSize();
			endIndex = endIndex > totalCount ? totalCount : endIndex;
			if (startIndex <= endIndex && startIndex != 0) {
				for (int i = startIndex; i <= endIndex; i++) {
					userIdList.add(idList.get(i - 1));
				}
			}
			count = totalCount;
		}
	}

	/**
	 * 
	 * 保存数据----保存到表与缓存中
	 *
	 * @author liuhaitao
	 * @param
	 * @return
	 * @throws Exception
	 * @exception
	 * @since JDK 1.8
	 */
//	private void saveStartMeet(StartMeetDto startMeetDto) throws Exception {
//		UserOnekeyEnity userOnkey = new UserOnekeyEnity();
//		userOnkey.setId(startMeetDto.getId());
//		userOnkey.setLngfloat(startMeetDto.getLngfloat());
//		userOnkey.setLatfloat(startMeetDto.getLatfloat());
//		userOnkey.setGeom(startMeetDto.getGeom());
//		userOnkey.setAddDate(new Date());
//		userOnkey.setAddTime(new Date());
//		userOnekeyDao.insert(userOnkey);
//
//		//只设置男或女的缓存数据
//		setMaleOrFemaleCache(startMeetDto);
//		//设置男女默认缓存数据
//		//		setDefaultCache(allList, startMeetDto);
//	}

	/**
	 * 设置男女默认缓存数据
	 */
	private void setDefaultCache(List<UserOnekeyEnity> allList, StartMeetDto startMeetDto) {
		UserInfoEnity userInfo = new UserInfoEnity();
		userInfo.setIs_register(1);
		List<UserInfoEnity> userList = userInfoDao.select(userInfo);
		Set<String> idSet = new HashSet<String>();
		if (!CollectionUtils.isEmpty(userList) && userList.size() > 0) {
			userList.stream().forEach(user -> {
				idSet.add(user.getId() + "");
			});
		}
		//设置男女通用缓存数据
		Long count = redisService.count(geoDb);
		if (count == null || count == 0) {
			if (!CollectionUtils.isEmpty(allList) && allList.size() > 0) {
				for (UserOnekeyEnity userOnekey : allList) {
					if (idSet.contains(userOnekey.getId())) {
						redisService.geoadd(geoDb, userOnekey.getId(), userOnekey.getLngfloat().doubleValue(), userOnekey.getLatfloat()
								.doubleValue());
					}
				}
			}

		}
		if (idSet.contains(startMeetDto.getId())) {
			redisService.geoadd(geoDb, startMeetDto.getId(), startMeetDto.getLngfloat().doubleValue(), startMeetDto.getLatfloat()
					.doubleValue());
		}
	}

	/**
	 * 根据传入的性别设置男或女缓存中的数据
	 *
	 */
//	private void setMaleOrFemaleCache(StartMeetDto startMeetDto) {
//		//男女缓存数据；
//		Long geoDbCount = redisService.count(geoDb);
//		//男缓存数据
//		Long maleGeodbCount = redisService.count(maleGeodb);
//		//女缓存数据
//		Long femaleGeodbCount = redisService.count(femaleGeodb);
//		List<UserOnekeyEnity> allList = userOnekeyDao.findAll();
//		if (!CollectionUtils.isEmpty(allList) && allList.size() != 0) {
//
//			///男女缓存数据
//			if (geoDbCount == null || geoDbCount == 0) {
//				UserInfoEnity userInfo = new UserInfoEnity();
//				userInfo.setIs_register(1);
//				List<UserInfoEnity> userList = userInfoDao.select(userInfo);
//				Set<String> idSet = new HashSet<String>();
//				if (!CollectionUtils.isEmpty(userList) && userList.size() > 0) {
//					userList.stream().forEach(user -> {
//						idSet.add(user.getId() + "");
//					});
//				}
//
//				if (!CollectionUtils.isEmpty(allList) && allList.size() > 0) {
//					for (UserOnekeyEnity userOnekey : allList) {
//						if (idSet.contains(userOnekey.getId())) {
//							redisService.geoadd(geoDb, userOnekey.getId(), userOnekey.getLngfloat().doubleValue(), userOnekey.getLatfloat()
//									.doubleValue());
//						}
//					}
//				}
//
//			}
//			//男缓存数据
//			if (maleGeodbCount == null || maleGeodbCount == 0) {
//				UserInfoEnity userInfo = new UserInfoEnity();
//				userInfo.setIs_register(1);
//				userInfo.setSex(JianBaEnum.SexEnum.MALE.getValue());
//				List<UserInfoEnity> userList = userInfoDao.select(userInfo);
//				Set<String> idSet = new HashSet<String>();
//				if (!CollectionUtils.isEmpty(userList) && userList.size() > 0) {
//					userList.stream().forEach(user -> {
//						idSet.add(user.getId() + "");
//					});
//				}
//
//				if (!CollectionUtils.isEmpty(allList) && allList.size() > 0) {
//					for (UserOnekeyEnity userOnekey : allList) {
//						if (idSet.contains(userOnekey.getId())) {
//							redisService.geoadd(maleGeodb, userOnekey.getId(), userOnekey.getLngfloat().doubleValue(), userOnekey
//									.getLatfloat().doubleValue());
//						}
//					}
//				}
//
//			}
//			//女缓存数据
//			if (femaleGeodbCount == null || femaleGeodbCount == 0) {
//				UserInfoEnity userInfo = new UserInfoEnity();
//				userInfo.setIs_register(1);
//				userInfo.setSex(JianBaEnum.SexEnum.FEMALE.getValue());
//				List<UserInfoEnity> userList = userInfoDao.select(userInfo);
//				Set<String> idSet = new HashSet<String>();
//				if (!CollectionUtils.isEmpty(userList) && userList.size() > 0) {
//					userList.stream().forEach(user -> {
//						idSet.add(user.getId() + "");
//					});
//				}
//
//				if (!CollectionUtils.isEmpty(allList) && allList.size() > 0) {
//					for (UserOnekeyEnity userOnekey : allList) {
//						if (idSet.contains(userOnekey.getId())) {
//							redisService.geoadd(femaleGeodb, userOnekey.getId(), userOnekey.getLngfloat().doubleValue(), userOnekey
//									.getLatfloat().doubleValue());
//						}
//					}
//				}
//
//			}
//		}
//
//		UserInfoEnity user = userInfoDao.findById(Long.parseLong(startMeetDto.getId()));
//		if (user != null) {
//			//缓存当前用户数据
//			if (user.getSex().intValue() == JianBaEnum.SexEnum.FEMALE.getValue()) {
//				redisService.geoadd(femaleGeodb, startMeetDto.getId(), startMeetDto.getLngfloat().doubleValue(), startMeetDto.getLatfloat()
//						.doubleValue());
//			} else if (user.getSex().intValue() == JianBaEnum.SexEnum.MALE.getValue()) {
//				redisService.geoadd(maleGeodb, startMeetDto.getId(), startMeetDto.getLngfloat().doubleValue(), startMeetDto.getLatfloat()
//						.doubleValue());
//			}
//		}
//
//		redisService
//				.geoadd(geoDb, startMeetDto.getId(), startMeetDto.getLngfloat().doubleValue(), startMeetDto.getLatfloat().doubleValue());
//
//	}

	/**
	 * 用户信息 描述这个方法的作用，从上面一行开始，并按Ctrl+d删除该行
	 *
	 * @author liuhaitao
	 * @param
	 * @return
	 * @exception
	 * @since JDK 1.8
	 */
	private Map<Long, UserInfoEnity> assembleUserInfo(List<Long> idList) {
		Map<Long, UserInfoEnity> nickNameMap = new HashMap<Long, UserInfoEnity>();
		List<UserInfoEnity> resuList = findBatchByUserIdList(idList);
		if (!CollectionUtils.isEmpty(resuList)) {
			resuList.stream().forEach(userInfo -> {
				nickNameMap.put(userInfo.getId(), userInfo);
			});
		}
		return nickNameMap;
	}

	/**
	 * 批量查询用户
	 * 
	 * @param idList
	 * @return
	 */
	private List<UserInfoEnity> findBatchByUserIdList(List<Long> idList) {
		List<UserInfoEnity> resuList = new ArrayList<UserInfoEnity>();
		if (!CollectionUtils.isEmpty(idList)) {
			List<List<Long>> listLists = ListUtil.splitList(idList, Constants.CUT_LIST_SIZE);
			listLists.stream().forEach(list -> {
				List<UserInfoEnity> userList = this.userInfoDao.findByUserIdList(list);
				if (!CollectionUtils.isEmpty(userList)) {
					resuList.addAll(userList);
				}
			});
		}
		return resuList;
	}

	/**
	 * 短信提醒对方用户,插入约见数据
	 * 
	 * @author liuhaitao
	 * @param inviteMeetDto
	 * @return
	 * @throws ClientException
	 *
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public List<StartMeetResultDto> inviteMeet(InviteMeetDto inviteMeetDto) throws Exception {
		//判断是两人关系
		UserRelationEntity userRelationEntity=new UserRelationEntity();
		userRelationEntity.setUserId(Long.parseLong(inviteMeetDto.getId()));
		userRelationEntity.setRelationId(Long.parseLong(inviteMeetDto.getMatchId()));
		List<UserRelationEntity> list=userRelationDao.eachOther(userRelationEntity);
		if(!CollectionUtils.isEmpty(list)){
			list.stream().forEach(each ->{
				if(each.getRelation().equals(JianBaEnum.RelationEnum.BLACK.getVal())){
					if(inviteMeetDto.getId().equals(String.valueOf(each.getUserId()))){
						throw new ResponseCodeAwareException(ResponseCode.ERROR,"您已拉黑对方");
					}else{
						throw new ResponseCodeAwareException(ResponseCode.ERROR,"您已被对方拉黑");
					}
				}
				if(each.getRelation().equals(JianBaEnum.RelationEnum.CHANGE.getVal())){
					if(inviteMeetDto.getId().equals(String.valueOf(each.getUserId()))){
						throw new ResponseCodeAwareException(ResponseCode.ERROR,"您已被对方拉黑");
					}else{
						throw new ResponseCodeAwareException(ResponseCode.ERROR,"您已拉黑对方");
					}
				}
				
			});
		}
		//1.如果存在 0:约见中； 提示用户已经约过对方，不能继续约
		//2.如果只存在非约见中的状态说明约见已经闭环，可以重新创建约见请求
		OnekeyMatchEntity check = new OnekeyMatchEntity();
		check.setId(inviteMeetDto.getId());
		check.setMatchId(inviteMeetDto.getMatchId());

		check.setMatchStatus(JianBaEnum.MeetMatchEnum.IN.getValue());
        List<OnekeyMatchEntity> matchList = onekeyMatchDao.select(check);
        if(!CollectionUtils.isEmpty(matchList)){
        	throw new ResponseCodeAwareException(ResponseCode.ERROR, "您已约过对方");
        }
        OnekeyMatchEntity enity = new OnekeyMatchEntity();

		enity.setId(inviteMeetDto.getId());
		enity.setMatchId(inviteMeetDto.getMatchId());
		enity.setMatchStatus(JianBaEnum.MeetMatchEnum.IN.getValue());
		enity.setLatfloat(inviteMeetDto.getLatfloat());
		enity.setLngfloat(inviteMeetDto.getLngfloat());
		enity.setSiteId(inviteMeetDto.getSiteId());
		enity.setAddDate(new Date());
		enity.setAddTime(new Date());

		enity.setSiteName(inviteMeetDto.getSiteName());
		onekeyMatchDao.insert(enity);
//		List<OnekeyMatchEntity> meetList = new ArrayList<OnekeyMatchEntity>();
//		List<OnekeyMatchEntity> needToMeetList = new ArrayList<OnekeyMatchEntity>();
		
//		if (!CollectionUtils.isEmpty(matchList) || matchList.size() > 0) {
//			needToMeetList = matchList
//					.stream()
//					.filter(enity -> (JianBaEnum.MeetMatchEnum.IN.getValue().equals(enity.getMatchStatus()) || JianBaEnum.MeetMatchEnum.SUCCESS
//							.getValue().equals(enity.getMatchStatus()))).collect(Collectors.toList());
//
//			meetList = matchList
//					.stream()
//					.filter(enity -> !(JianBaEnum.MeetMatchEnum.IN.getValue().equals(enity.getMatchStatus()) || JianBaEnum.MeetMatchEnum.SUCCESS
//							.getValue().equals(enity.getMatchStatus()))).collect(Collectors.toList());
//		}


		UserInfoEnity userInfo = new UserInfoEnity();
		userInfo.setId(Long.parseLong(inviteMeetDto.getMatchId()));
		userInfo.setIs_register(1);
		List<UserInfoEnity> user = userInfoDao.select(userInfo);
		if (!CollectionUtils.isEmpty(user) && user.size() > 0) {
			JSONObject smsContent = new JSONObject();
			smsContent.put("user_id", user.get(0).getNickname());
			SMSUtils.sendMeetSms(user.get(0).getMobile(), smsContent.toJSONString());
		}

		// 如果是非官方地址
		if (inviteMeetDto.getIsAuthority() != null && inviteMeetDto.getIsAuthority() == 0) {
			SiteListEntity siteEnity = siteListService.findBySiteId(inviteMeetDto);
			if (siteEnity == null) {
				SiteListEntity saveSiteEnity = new SiteListEntity();
				saveSiteEnity.setSiteId(inviteMeetDto.getSiteId());
				saveSiteEnity.setSiteType(5L);
				saveSiteEnity.setSiteTypeName("自定义");
				saveSiteEnity.setIsAuthority(inviteMeetDto.getIsAuthority());
				saveSiteEnity.setLatfloat(inviteMeetDto.getLatfloat());
				saveSiteEnity.setLngfloat(inviteMeetDto.getLngfloat());
				saveSiteEnity.setSiteName(inviteMeetDto.getSiteName());
				siteListService.save(saveSiteEnity);
			}
		}

		return null;
	}

	/**
	 * 用户同意对方的约见
	 *
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void agreeMeet(AgreeMeetDto agreeMeetDto) {
		OnekeyMatchEntity enity = new OnekeyMatchEntity();
		enity.setId(agreeMeetDto.getMatchId());
		enity.setMatchId(agreeMeetDto.getId());
		enity.setMatchStatus(JianBaEnum.MeetMatchEnum.SUCCESS.getValue());
		int line = onekeyMatchDao.update(enity);
		if(line==0){
			throw new BusinessException(ResponseCode.ERROR, "状态已变更!");
		}
		LOGGER.info("----MeetServiceImpl----agreeMeet----------" + line);
	}

	/**
	 * 用户拒绝对方约见，从缓存，数据库中清除该用户
	 * 
	 * @param cancleMeetDto
	 *
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void refuseMeet(RefuseMeetDto refuseMeetDto) {
		OnekeyMatchEntity enity = new OnekeyMatchEntity();
		enity.setId(refuseMeetDto.getMatchId());
		enity.setMatchId(refuseMeetDto.getId());
		enity.setMatchStatus(JianBaEnum.MeetMatchEnum.FAILE.getValue());
		int line = onekeyMatchDao.update(enity);
		if(line==0){
			throw new BusinessException(ResponseCode.ERROR, "状态已变更!");
		}
		LOGGER.info("----MeetServiceImpl----refuseMeet----------" + line);
	}

	/**
	 * 用户主动取消约见功能，从缓存，数据库中清除该用户
	 * 
	 * @author liuhaitao
	 * @param cancleMeetDto
	 *
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void cancleMeet(CancleMeetDto cancleMeetDto) {
		LOGGER.info("----MeetServiceImpl----cancleMeet----------");
//		userOnekeyDao.delete(cancleMeetDto.getId());
//		redisService.removeGeo(geoDb, cancleMeetDto.getId());
//
//		UserInfoEnity userInfo = userInfoDao.findById(Long.parseLong(cancleMeetDto.getId()));
//		if (userInfo != null && userInfo.getSex() != null) {
//			//如果是男
//			if (userInfo.getSex() == 0) {
//				redisService.removeGeo(maleGeodb, cancleMeetDto.getId());
//			} else if (userInfo.getSex() == 1) {
//				redisService.removeGeo(femaleGeodb, cancleMeetDto.getId());
//			}
//		}
		EsServiceResult result=yueJianService.deleteDocByDocId(cancleMeetDto.getId());
		if(result.getStatus()==EsServiceResult.ResultStatus.DELETED.getValue()){
			return;
		}else if(result.getStatus()==EsServiceResult.ResultStatus.NOT_FOUND.getValue()){
			return;
		}else if(result.getStatus()==EsServiceResult.ResultStatus.CONFLICT.getValue()){
			throw new BusinessException(ResponseCode.ERROR, "CONFLICT");
		}else{
			throw new BusinessException(ResponseCode.ERROR, "操作失败");
		}

	}

	/**
	 * 用户针对某个用户撤销约见
	 * 
	 * @description (这里用一句话描述这个方法的作用).
	 * @author liuhaitao
	 * @param revokeMeetDto
	 *
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void revokeMeet(RevokeMeetDto revokeMeetDto) {
		OnekeyMatchEntity enity = new OnekeyMatchEntity();
		enity.setId(revokeMeetDto.getId());
		enity.setMatchId(revokeMeetDto.getMatchId());
		enity.setMatchStatus(JianBaEnum.MeetMatchEnum.REVOKE.getValue());
		int line = onekeyMatchDao.update(enity);
		if(line==0){
			throw new BusinessException(ResponseCode.ERROR, "状态已变更!");
		}
		LOGGER.info("----MeetServiceImpl----cancleMeet----------" + line);

	}

	@Transactional(rollbackFor = Exception.class)
	private List<OnekeyMatchEntity> checkStatus(String id, String matchId, String matchStatus) {
		OnekeyMatchEntity enity = new OnekeyMatchEntity();
		enity.setId(id);
		enity.setMatchId(matchId);
		enity.setMatchStatus(matchStatus);
		return onekeyMatchDao.select(enity);
	}

	/**
	 * 约见地址
	 * 
	 * @author liuhaitao
	 * @return
	 *
	 */
	@Override
	public List<MeetAddressDto> meetAddress() {
		Map<Pair<Long, String>, List<MeetAddressVo>> addressMap = new LinkedHashMap<Pair<Long, String>, List<MeetAddressVo>>();
		List<MeetAddressDto> resultList = new ArrayList<MeetAddressDto>();
//		List<SiteListEntity> siteList = siteListService.findAll();
		List<ShopListEntity> shopList=shopListDao.selectAll(new ShopListEntity());
		if (!CollectionUtils.isEmpty(shopList) && shopList.size() > 0) {
			for (ShopListEntity site : shopList) {
				Pair<Long, String> pair = new ImmutablePair<Long, String>(site.getShop_type().longValue(), site.getSite_name());
				if (addressMap.containsKey(pair)) {
					List<MeetAddressVo> address = addressMap.get(site.getShop_type());
					address.add(new MeetAddressVo(site.getSite_id(), new BigDecimal(site.getLngfloat()), new BigDecimal(site.getLatfloat()), site.getSite_name()));
				} else {
					List<MeetAddressVo> address = new ArrayList<MeetAddressVo>();
					address.add(new MeetAddressVo(site.getSite_id(), new BigDecimal(site.getLngfloat()), new BigDecimal(site.getLatfloat()), site.getSite_name()));
					addressMap.put(pair, address);
				}
			}
			Iterator<Pair<Long, String>> linkMapIt = addressMap.keySet().iterator();
			while (linkMapIt.hasNext()) {
				MeetAddressDto dto = new MeetAddressDto();
				Pair<Long, String> pair = linkMapIt.next();
				dto.setSiteType(pair.getLeft());
				dto.setSiteName(pair.getRight());
				dto.setAddress(addressMap.get(pair));
				resultList.add(dto);
			}

		}
		return resultList;
	}

	/**
	 * 我约列表
	 * 
	 * @description (这里用一句话描述这个方法的作用).
	 * @author liuhaitao
	 * @param meetListDto
	 * @return
	 * @throws IOException 
	 *
	 */
	@Override
	public Page<MeetListResultDto> meetList(MeetListDto meetListDto) throws IOException {
		List<OnekeyMatchEntity> matchList = onekeyMatchDao.findPage(meetListDto);
		Integer count = onekeyMatchDao.findPageCount(meetListDto);
		List<MeetListResultDto> resultList = new ArrayList<MeetListResultDto>();

		if (!CollectionUtils.isEmpty(matchList)) {
			List<Long> userIdList = new ArrayList<Long>();
			List<Long> meetIdList = new ArrayList<Long>();
			Map<Long, OnekeyMatchEntity> addreMap = new HashMap<Long, OnekeyMatchEntity>();
			matchList.forEach(match -> {
				long id = Long.parseLong(match.getMatchId());
				userIdList.add(id);
				meetIdList.add(match.getMeetId());
				addreMap.put(match.getMeetId(), match);
			});

			// key =userId ,value= UserInfoEnity
			Map<Long, UserInfoEnity> userInfoMap = assembleUserInfo(userIdList);

			for (int i=0;i<meetIdList.size();i++) {
				MeetListResultDto resultDto = new MeetListResultDto();
				resultDto.setId(userIdList.get(i));
				OnekeyMatchEntity onekeyMatch = addreMap.get(meetIdList.get(i));
				resultDto.setAddress(onekeyMatch.getSiteName());
				resultDto.setStatus(onekeyMatch.getMatchStatus());
				resultDto.setTime(DateUtil.format(onekeyMatch.getAddDate(),"yyyy-MM-dd"));
				if (userInfoMap != null && userInfoMap.get(userIdList.get(i)) != null) {
					UserInfoEnity userInfo = userInfoMap.get(userIdList.get(i));
					setMeetListDefaultValue(resultDto, userInfo);
				}
				//新增返回时间和主题
				resultDto.setTime(DateUtil.format(onekeyMatch.getAddDate(),"yyyy-MM-dd"));
				EsServiceResult result=yueJianService.findByUid(meetListDto.getId());
				if(result.getStatus()==EsServiceResult.ResultStatus.SUCCESS.getValue()){
					Object theme=result.getMap().get(EsUtil.theme);
					resultDto.setTheme(theme==null?"":(String)theme);
				}else if(result.getStatus()==EsServiceResult.ResultStatus.NOT_FOUND.getValue()){
					resultDto.setTheme("");
				}else{
					throw new BusinessException(ResponseCode.ERROR, "请求失败");
				}
				resultList.add(resultDto);
			}
		}

		Pageable pageable = new Pageable(meetListDto.getPageNumber(), meetListDto.getPageSize());
		Page<MeetListResultDto> pageVo = new Page<MeetListResultDto>(resultList, count, pageable);

		return pageVo;
	}

	private void setMeetListDefaultValue(MeetListResultDto resultDto, UserInfoEnity userInfo) {
		if (userInfo != null) {
			if (StringUtils.isBlank(userInfo.getNickname())) {
				if (userInfo.getSex() != null && userInfo.getSex().intValue() == 0) {
					resultDto.setNickname("帅哥");
				} else {
					resultDto.setNickname("美女");
				}
			} else {
				resultDto.setNickname(userInfo.getNickname());
			}

			if (userInfo.getBirthday() != null) {
				Date bir = DateUtil.parse("1991-01-01");
				resultDto.setAge(DateUtil.getAge(bir));
			} else {
				resultDto.setAge(DateUtil.getAge(userInfo.getBirthday()));
			}

			if (userInfo.getBirthday() == null) {
				Date bir = DateUtil.parse("1991-01-01");
				resultDto.setConstellation(DateUtil.getConstellation(bir));
			} else {
				resultDto.setConstellation(DateUtil.getConstellation(userInfo.getBirthday()));
			}
			resultDto.setSex(userInfo.getSex());
			resultDto.setUserLogo(userInfo.getUserLogo());

		}

	}

	/**
	 * 约我列表
	 * 
	 * @author liuhaitao
	 * @param meetListDto
	 * @return
	 * @throws IOException 
	 *
	 */
	@Override
	public Page<MeetListResultDto> listMe(MeetListDto meetListDto) throws IOException {
		List<OnekeyMatchEntity> matchList = onekeyMatchDao.findPageListMe(meetListDto);
		Integer count = onekeyMatchDao.findPageListMeCount(meetListDto);
		List<MeetListResultDto> resultList = new ArrayList<MeetListResultDto>();

		if (!CollectionUtils.isEmpty(matchList)) {
			List<Long> userIdList = new ArrayList<Long>();
			List<Long> meetIdList = new ArrayList<Long>();
			Map<Long, OnekeyMatchEntity> addreMap = new HashMap<Long, OnekeyMatchEntity>();
			matchList.forEach(match -> {
				long id = Long.parseLong(match.getId());
				userIdList.add(id);
				meetIdList.add(match.getMeetId());
				addreMap.put(match.getMeetId(), match);
			});

			// key =userId ,value= UserInfoEnity
			Map<Long, UserInfoEnity> userInfoMap = assembleUserInfo(userIdList);

			for (int i=0;i<meetIdList.size();i++) {
				MeetListResultDto resultDto = new MeetListResultDto();
				resultDto.setId(userIdList.get(i));
				OnekeyMatchEntity onekeyMatch = addreMap.get(meetIdList.get(i));
				resultDto.setAddress(onekeyMatch.getSiteName());
				resultDto.setStatus(onekeyMatch.getMatchStatus());
				resultDto.setTime(DateUtil.format(onekeyMatch.getAddDate(),"yyyy-MM-dd"));
				if (userInfoMap != null && userInfoMap.get(userIdList.get(i)) != null) {
					UserInfoEnity userInfo = userInfoMap.get(userIdList.get(i));
					setMeetListDefaultValue(resultDto, userInfo);
				}
				//新增返回时间和主题
				resultDto.setTime(DateUtil.format(onekeyMatch.getAddDate(),"yyyy-MM-dd"));
				EsServiceResult result=yueJianService.findByUid(String.valueOf(userIdList.get(i)));
				if(result.getStatus()==EsServiceResult.ResultStatus.SUCCESS.getValue()){
					Object theme=result.getMap().get(EsUtil.theme);
					resultDto.setTheme(theme==null?"":(String)theme);
				}else if(result.getStatus()==EsServiceResult.ResultStatus.NOT_FOUND.getValue()){
					resultDto.setTheme("");
				}else{
					throw new BusinessException(ResponseCode.ERROR, "请求失败");
				}
				resultList.add(resultDto);
			}
		}

		Pageable pageable = new Pageable(meetListDto.getPageNumber(), meetListDto.getPageSize());
		Page<MeetListResultDto> pageVo = new Page<MeetListResultDto>(resultList, count, pageable);

		return pageVo;
	}

}
